import GetPageComponents from '@/components/GetPageComponents';
import ToTop from '@/components/toTop';
import ModelAgreementAccess from '@/components/ModelAgreementAccess';
import ModelCoupon from '@/components/ModelCoupon';
import { EventNames, useEventCenterOn } from '@/dataTransfer/eventCenter';
import UnusualContain from '@/pages/mainPages/unusualContain/index';
import utils from '@/utils/index';
import { Button, View, Image, Text } from '@tarojs/components';
import Taro, { getCurrentInstance, useDidShow } from '@tarojs/taro';
import React, { useEffect, useRef, useState } from 'react';
import { connect } from 'react-redux';
import './homePage.scss';

const HomePage = ({ agreementAccessIsShow }) => {
  let capsuleInfo = {}
  if(process.env.TARO_ENV != 'h5') capsuleInfo = Taro.getMenuButtonBoundingClientRect()
  const [cinemaInfo,setCinemaInfo] = useState({})
  const [shouldShow, setShouldShow] = useState(false);
  const [curLocation, setCurLocation] = useState(null);
  const [scrollTop, setScrollTop] = useState(null);
  const [colorConfig, setcolorConfig] = useState({})
  const urlParms = useRef({ display: false });

  useDidShow(() => {
    utils.getDirectionalCoupons();
    let unusualInfo = utils.getLocalStorage('unusualInfo');
    if (unusualInfo !== null) {
      utils.setLocalStorage('unusualInfo', null);
    }
  });

  useEffect(() => {
    urlParms.current = getCurrentInstance().router.params || {};
    if (Taro.$isH5 && urlParms.current.from == 'wxPay') {
    } else {
      let localLocation = utils.getLocalEffectLocation();
      if (localLocation) {
        const { latitude, longitude } = localLocation;
        setCurLocation({ latitude, longitude });
      }
    }
    setShouldShow(true);
    if(Taro.getStorageSync('merchantId')){
      setCinemaInfo(Taro.getStorageSync('selectMerchant'))
    }
    Taro.eventCenter.on('updateMerchant',e=>{
      setCinemaInfo(Taro.getStorageSync('selectMerchant'))
    })
  }, []);

  useEffect(() => {
    if (!curLocation && shouldShow) {
      getLocation();
    }
  }, [shouldShow]);

  const getLocation = () => {
    // Taro.getLocation({
    //   type: 'gcj02',
    //   isHighAccuracy: true,
    //   timeout: 5000,
    //   success: (res) => {
    //     const { latitude, longitude } = res;
    //     const timeStamp = new Date().getTime();
    //     setCurLocation({ latitude, longitude });
    //     utils.setLocalStorage('location', { latitude, longitude, timeStamp });
    //   },
    //   fail: () => {},
    // }).catch(console.warn);
  };

  // 滚动监听
  useEventCenterOn(
    EventNames.ModuleScroll,
    ({ event, pageName: scrollPageName }) => {
      // 不是同一个页面的滚动
      if (scrollPageName !== 'home') {
        return;
      }

      setScrollTop(event?.detail?.scrollTop ?? 0);
    },
    [],
  );

  if (Taro.$isH5 && urlParms.current.from == 'wxPay') {
    return <GoOrederDetail orderId={urlParms.current.orderId} />;
  }

  let unusualInfo = utils.getLocalStorage('unusualInfo');

  return (
    <View className={`totalPage_homePage ${process.env.TARO_ENV}`}>
      <View className="home-nav-bar" style={{paddingTop:capsuleInfo.top+'PX'}}>
        <View className="box-flex" style={{minHeight: capsuleInfo.height+'px'}} onClick={()=>{
          Taro.navigateTo({
            url:'/mainPages/select-cinema/index'
          })
        }}>
          {cinemaInfo.cinemaNickName || "请选择影院"}
          <Text className='at-icon at-icon-chevron-down' style={{marginLeft:4}}></Text>
          {cinemaInfo.distance?<View className="distance">距离您 {cinemaInfo.distance}</View>:null}
        </View>
      </View>
      {unusualInfo ? (
        <UnusualContain unusualInfo={unusualInfo} />
      ) : (
        <>
          <ToTop
            top="2856"
            scrollTop={scrollTop}
            handleToTopScrollView={(e) => {
              Taro.eventCenter.trigger(EventNames.SetModuleScroll, {
                event: e,
                pageName: 'home',
                value: 0,
              });
            }}
          />
          <ModelAgreementAccess />
          {agreementAccessIsShow === false && <ModelCoupon />}
          <GetPageComponents pageName="home" />
        </>
      )}
    </View>
  );
};

const GoOrederDetail = ({ orderId }) => {
  const orderDetailRef = useRef(null);

  const goOrderDetail = () => {
    let url = '/orderSubPack/orderDetail/index?orderId=' + orderId;
    window.location.href = url;
  };

  useEffect(() => {
    orderDetailRef && orderDetailRef.current.click();
  }, []);

  return (
    <View className="totalPage_homePage">
      <Button className="orderDetail" ref={orderDetailRef} onClick={goOrderDetail}></Button>
    </View>
  );
};

export default connect(({ loading, otherApi }) => ({
  loading,
  agreementAccessIsShow: otherApi.agreementAccessIsShow,
}))(HomePage);
